package com.play.ballen.home.ui

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.View.OnClickListener
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.hjq.toast.ToastUtils
import com.play.ballen.R
import com.play.ballen.databinding.ActivityMainBinding
import com.play.ballen.event.EventCost
import com.play.ballen.home.task.StepServiceUtil
import com.play.ballen.home.task.TaskUtil
import com.play.ballen.home.ui.fragment.PlPFragment
import com.play.ballen.home.vm.HomeFragmentVM
import com.play.ballen.mall.ui.MallFragment
import com.play.ballen.mall.ui.im.IMFragment
import com.play.ballen.me.ui.LoginActivity
import com.play.ballen.me.ui.MeFragment
import com.play.ballen.synthetic.ui.SyntheticFragment
import com.play.ballen.utils.GifUtil
import com.play.ballen.utils.UserInfoManager
import com.yuven.appframework.adapter.MainPagerAdapter
import com.yuven.appframework.manager.AppActivitysManager
import com.yuven.baselib.component.BaseMVVMActivity
import com.yuven.baselib.component.eventbus.Event
import com.yuven.baselib.utils.Logger
import com.yuven.baselib.utils.ResourceUtil

class MainActivity : BaseMVVMActivity<HomeFragmentVM, ActivityMainBinding>(),
    OnClickListener {

    private val fragmentHome by lazy { PlPFragment.newInstance() }
    private val fragmentMall by lazy { MeFragment.newInstance() }
    private val fragmentSynthetic by lazy { MeFragment.newInstance() }
    private val fragmentPack by lazy { IMFragment.newInstance() }
    private val fragmentMe by lazy { MeFragment.newInstance() }

    private var mAdapter: MainPagerAdapter? = null
    private val fragments by lazy {
        arrayListOf<Fragment>(
            fragmentHome,
            fragmentMall,
            fragmentSynthetic,
            fragmentPack,
            fragmentMe
        )
    }
    private var mSelectedIndex = -1

    companion object {

        private const val TAB_HOME = 0
        private const val TAB_MALL = 1
        private const val TAB_SYNTHETIC = 2
        private const val TAB_PACK = 3
        private const val TAB_ME = 4

        @JvmStatic
        fun start(context: Context) {
            val starter = Intent(context, MainActivity::class.java)
            context.startActivity(starter)
        }
    }

    override fun layoutId(): Int = R.layout.activity_main

    override fun viewModelClass(): Class<HomeFragmentVM> {
        return HomeFragmentVM::class.java
    }

    override fun initView() {
        ImmersionBar.with(this).init();
        GifUtil.setDrawable(dataBinding.ivTabOne,R.drawable.main_1,R.drawable.piaoliuping_gif)
        GifUtil.setDrawable(dataBinding.ivTabTwo,R.drawable.main_2,R.drawable.dongtai_gif)
        GifUtil.setDrawable(dataBinding.ivTabFour,R.drawable.main_3,R.drawable.chat_gif)
        GifUtil.setDrawable(dataBinding.ivTabFive,R.drawable.main_4,R.drawable.me_gif)

        mAdapter = MainPagerAdapter(supportFragmentManager, fragments)
        dataBinding.vp.adapter = mAdapter
        dataBinding.vp.offscreenPageLimit = fragments.size
        dataBinding.vp.addOnPageChangeListener(object :
            ViewPager.SimpleOnPageChangeListener() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                mSelectedIndex = position
            }
        })

        switchToTab(TAB_HOME)
        viewModel.getUserInfo()
        if(UserInfoManager.getUserInfo()?.needInfo() == true){//第一次进入没有头像 去设置
//            UserInfoManager.getUserInfo()?.info?.let { it1 ->
//                AddInformationActivity.start(mContext, it1.avatar_url,it1.nickname)
//            }
        }
    }

    override fun initData() {
        dataBinding.llTabOne.setOnClickListener(this)
        dataBinding.llTabTwo.setOnClickListener(this)
        //dataBinding.tab.tabSynthetic.setOnClickListener(this)
        dataBinding.llTabThree.setOnClickListener(this)
        dataBinding.llTabFour.setOnClickListener(this)
        dataBinding.llTabFive.setOnClickListener(this)

//        fragmentHome.apply {
//            startRegisterStepSensor = {
//                StepServiceUtil.registerSensor(this@MainActivity)
//            }
//
//            stepSensorAvailable = {
//                StepServiceUtil.stepSensorAvailable()
//            }
//        }
    }

    override fun initIntent(intent: Intent?) {

    }

    override fun registerEventBus(): Boolean {
        return true
    }

    override fun handleEvent(event: Event<Any>) {
        super.handleEvent(event)
        when (event.code) {
            EventCost.CODE_LOGIN_STATUS_FAILURE -> {
                Logger.i("Receive token failure event")
                ToastUtils.show(ResourceUtil.getString(R.string.login_expired_tips))
                UserInfoManager.logout()
                AppActivitysManager.getInstance().finishAllActivity()
                LoginActivity.start(this)
            }

            EventCost.CODE_LOGOUT -> {
                Logger.i("MainActivity.handleEvent CODE_LOGOUT")
                TaskUtil.releaseAll()
                StepServiceUtil.unregisterSensor()
            }
        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.ll_tab_one -> {
                switchToTab(TAB_HOME)
            }

            R.id.ll_tab_two -> {
                switchToTab(TAB_MALL)
            }

            R.id.ll_tab_three -> {
                switchToTab(TAB_SYNTHETIC)
            }

            R.id.ll_tab_four -> {
                switchToTab(TAB_PACK)
            }

            R.id.ll_tab_five -> {
                switchToTab(TAB_ME)
            }
        }
    }

    private fun switchToTab(index: Int) {
        Logger.i("MainActivity.switchToTab index = $index, mCurrentSelectedIndex = $mSelectedIndex")
        if (index == mSelectedIndex) {
            return
        }
        setTabStatus(index)
        changeStatusBar(index)
        dataBinding.vp.setCurrentItem(index, false)
    }

    private fun setTabStatus(index: Int) {
        dataBinding.ivTabOne.isSelected = index == TAB_HOME
        dataBinding.ivTabTwo.isSelected = index == TAB_MALL
        dataBinding.ivTabFour.isSelected = index == TAB_PACK
        dataBinding.ivTabFive.isSelected = index == TAB_ME
    }
    fun changeStatusBar(tabPosition: Int) {
        when (tabPosition) {
            0 -> ImmersionBar.with(this)
                .fitsSystemWindows(false)
                .statusBarColor(android.R.color.transparent)
                .statusBarDarkFont(false)
                .hideBar(BarHide.FLAG_SHOW_BAR)
                .init()

            3 -> ImmersionBar.with(this)
                .fitsSystemWindows(false)
                .statusBarColor(android.R.color.transparent)
                .statusBarDarkFont(false)
                .hideBar(BarHide.FLAG_SHOW_BAR)
                .init()

            1, 2 -> ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarColor(R.color.white)
                .statusBarDarkFont(true)
                .hideBar(BarHide.FLAG_SHOW_BAR)
                .init()
        }
    }


    override fun onBackPressed() {
        if (mSelectedIndex != TAB_HOME) {
            switchToTab(TAB_HOME)
        } else {
            moveTaskToBack(true)
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        outState.putInt("tabIndex", mSelectedIndex)
        super.onSaveInstanceState(outState)
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
        mSelectedIndex = savedInstanceState.getInt("tabIndex")
        setTabStatus(mSelectedIndex)
    }

    override fun onDestroy() {
        super.onDestroy()
    }

}